import { HttpException, Injectable } from '@nestjs/common';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Permission } from './entities/permission.entity';
import { Repository } from 'typeorm';
import { PaginationService } from '../../common/pagination/pagination.service';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private readonly permissionRepositoty: Repository<Permission>,
    private pageService: PaginationService<Permission>,
  ) {
    this.pageService = new PaginationService<Permission>(
      this.permissionRepositoty,
    );
  }

  async create(createPermissionDto: CreatePermissionDto) {
    const data = this.permissionRepositoty.create(createPermissionDto);
    return await this.permissionRepositoty.save(data);
  }

  async findAll(params: { page: number; pageSize: number }) {
    const res = await this.pageService.paginate({
      ...params,
    });
    return res;
  }

  // 分页查询
  async pageSearch(params: {
    page: number;
    pageSize: number;
    name: string;
    code: string;
  }) {
    const { page, pageSize, name, code } = params;
    // 定义查询构造器
    const qb = this.permissionRepositoty.createQueryBuilder();
    // 模糊查询name、code
    name && qb.andWhere('name like :name', { name: `%${name}%` });
    code && qb.andWhere('code like :code', { code: `%${code}%` });
    // 连表查询
    qb.relation('permissions');
    // console.log('pageSearch params', params);
    // 分页查询
    return this.pageService.pageSearch({
      page,
      pageSize,
      queryBuilder: qb,
    });
  }

  async findOne(id: string) {
    return await this.permissionRepositoty.findOneBy({ id });
  }

  async update(id: string, updatePermissionDto: UpdatePermissionDto) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    const updateData = this.permissionRepositoty.merge(
      data,
      updatePermissionDto,
    );
    return await this.permissionRepositoty.save(updateData);
  }

  async remove(id: string) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    return await this.permissionRepositoty.delete({ id });
  }
}
